package org.jetlinks.pro.cassandra.metadata;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * Cassandra 主键定义,支持嵌套:
 * <pre>{@code
 *   of("deviceId","property") => (deviceId,property)
 *   of("deviceId","property",of("timestamp")) => (deviceId,property,(timestamp))
 * }</pre>
 *
 * @author zhouhao
 * @since 1.10
 * @see CassandraPrimaryKeyBuilder
 */
@Getter
@Setter
@AllArgsConstructor(staticName = "of")
@NoArgsConstructor
public class CassandraPrimaryKey {

    private CassandraPrimaryKey pre;

    private List<String> column;

    private CassandraPrimaryKey next;

    public static CassandraPrimaryKey of(String... column) {
        return of(null, Arrays.asList(column), null);
    }

    public static CassandraPrimaryKey of(CassandraPrimaryKey pre, String... column) {
        return of(pre, Arrays.asList(column), null);
    }

    public static CassandraPrimaryKey of(CassandraPrimaryKey pre, CassandraPrimaryKey next) {
        return new CassandraPrimaryKey(pre, null, next);
    }

    public static CassandraPrimaryKey of(List<String> columns, CassandraPrimaryKey next) {
        return new CassandraPrimaryKey(null, columns, next);
    }

    public boolean containsColumn(String column) {
        boolean contains = this.column != null && this.column.contains(column);
        if (contains) {
            return true;
        }
        contains = pre != null && pre.containsColumn(column);
        if (contains) {
            return true;
        }
        return next != null && next.containsColumn(column);

    }

    public String toSql() {
        StringBuilder builder = new StringBuilder();

        if (pre != null) {
            builder.append("(").append(pre.toSql()).append(")");
        }
        if (!CollectionUtils.isEmpty(column)) {
            if (builder.length() > 0) {
                builder.append(",");
            }
            for (int i = 0, size = column.size(); i < size; i++) {
                if (i > 0) {
                    builder.append(",");
                }
                builder.append("\"").append(column.get(i)).append("\"");
            }
        }
        if (next != null) {
            if (builder.length() > 0) {
                builder.append(",");
            }
            builder.append("(").append(next.toSql()).append(")");
        }

        return builder.toString();
    }

    @Override
    public String toString() {
        return toSql();
    }
}

//(a,v),a